﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Tools.Models;
using Tools.Service;
using Tools.Utils;

namespace Tools.Controllers
{
    public class ImageController : Controller
    {
        private readonly ILogger<HomeController> _logger;

        public ImageController(ILogger<HomeController> logger)
        {
            _logger = logger;
        }

        /// <summary>
        /// 图片缩放
        /// </summary>
        /// <param name="formCollection"></param>
        /// <returns></returns>
        public IActionResult ZoomImage(FormCollection formCollection)
        {
            FormFileCollection filelist = (FormFileCollection)formCollection.Files ?? new FormFileCollection();
            var height = Convert.ToInt32(formCollection["height"]);
            var width = Convert.ToInt32(formCollection["width"]);

            if (filelist.Count() == 0)
            {
                ViewData["message"] = "请选择上传文件";
            }
            else
            {
                string filePath = $"{ System.AppDomain.CurrentDomain.BaseDirectory }/images/";
                DirectoryInfo di = new DirectoryInfo(filePath);
                if (!di.Exists) { di.Create(); }

                var url = filePath;
                var isOneFile = filelist.Count == 1;

                try
                {

                    if (!isOneFile)
                    {
                        url += Guid.NewGuid().ToString().Replace("-", "");
                        new DirectoryInfo(url).Create();
                    }

                    foreach (IFormFile file in filelist)
                    {
                        string name = file.FileName;
                        string fileName = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                        string type = System.IO.Path.GetExtension(name);
                        var path = url + fileName + type;

                        //处理图片
                        MemoryStream stream = new MemoryStream();
                        file.CopyTo(stream);
                        Bitmap bitmap = new Bitmap(stream);
                        new ImageService().ZoomImage(bitmap, height, width, path);
                        stream.Flush();
                        stream.Dispose();

                        if (isOneFile)
                        {
                            url = path;
                        }
                    }

                    if (!isOneFile)
                    {
                        new CompressHelper().CompressDirectory(url, $"{url}.zip", 9, false);
                    }

                    ViewData["url"] = isOneFile ? url : $"{url}.zip";
                }
                catch (Exception)
                {
                    ViewData["message"] = "程序异常，请稍后重试";
                    return View();
                }
            }

            return View();
        }

        /// <summary>
        /// 图片替换背景色
        /// </summary>
        /// <param name="formCollection"></param>
        /// <returns></returns>
        public IActionResult ImageBackgroundColor(FormCollection formCollection)
        {
            FormFileCollection filelist = (FormFileCollection)formCollection.Files ?? new FormFileCollection();
            var color = !string.IsNullOrWhiteSpace(formCollection["color"]) ? EnumHelper.ToEnum<Color>(formCollection["color"].ToString()) : Color.White;
            var type = Convert.ToInt32(formCollection["type"].ToString());

            if (filelist.Count() == 0)
            {
                ViewData["message"] = "请选择上传文件";
            }
            else
            {
                string filePath = $"{ System.AppDomain.CurrentDomain.BaseDirectory }/images/";
                DirectoryInfo di = new DirectoryInfo(filePath);
                if (!di.Exists) { di.Create(); }

                var url = filePath;
                var isOneFile = filelist.Count == 1;

                try
                {

                    if (!isOneFile)
                    {
                        url += Guid.NewGuid().ToString().Replace("-", "");
                        new DirectoryInfo(url).Create();
                    }

                    foreach (IFormFile file in filelist)
                    {
                        string name = file.FileName;
                        string fileName = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                        string suffix = System.IO.Path.GetExtension(name);
                        var path = url + fileName + suffix;

                        //处理图片
                        MemoryStream stream = new MemoryStream();
                        file.CopyTo(stream);
                        Bitmap bitmap = new Bitmap(stream);
                        new ImageService().ImageBackgroundColor(bitmap, path, color, type);
                        stream.Flush();
                        stream.Dispose();

                        if (isOneFile)
                        {
                            url = path;
                        }
                    }

                    if (!isOneFile)
                    {
                        new CompressHelper().CompressDirectory(url, $"{url}.zip", 9, false);
                    }

                    ViewData["url"] = isOneFile ? url : $"{url}.zip";
                }
                catch (Exception)
                {
                    ViewData["message"] = "程序异常，请稍后重试";
                    return View();
                }
            }

            return View();
        }
    }
}
